/**
 * IngresarFrame.java
 * @author Paulo Chang, Carnet 11076
 * @author Oscar Castañeda, Carnet 11086
 * @author Francisco Martínez, Carnet 11096
 * @since 06/11/2011
 * Modificado por última vez el 13/11/2011.
 * Descripción: Clase de interfaz gráfica utilizado para que el usuario pueda iniciar
 * su sesión en el programa.
 */

import javax.swing.JOptionPane;

public class IngresarFrame extends javax.swing.JFrame {
    
    //Atributos
    private Principal principal;
    
    /**
     * Permite crear un nuevo frame que contiene los elementos necesarios para
     * que un usuario inicie sesión o cree su cuenta.
     * @param principal Clase donde se ejecuta el método principal.
     */
    public IngresarFrame(Principal principal) {
        this.principal=principal;
        initComponents();
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        textFieldUsuario = new javax.swing.JTextField();
        fieldContrasena = new javax.swing.JPasswordField();
        botonAceptar = new javax.swing.JButton();
        botonDivertido = new javax.swing.JButton();
        pantallaError = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setText("<html><p align=center><big>Bienvenidos a la Super-Duper Billetera</big> <br>Ingrese su usuario y contraseña para poder<br> dominar al mundo</html> ");

        jLabel2.setText("Usuario:");

        jLabel3.setText("Contraseña");

        botonAceptar.setText("Aceptar");
        botonAceptar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botonAceptarActionPerformed(evt);
            }
        });

        botonDivertido.setText("Divertido");
        botonDivertido.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botonDivertidoActionPerformed(evt);
            }
        });

        pantallaError.setBackground(java.awt.Color.lightGray);
        pantallaError.setForeground(java.awt.Color.red);
        pantallaError.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(29, 29, 29)
                        .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 409, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(100, 100, 100)
                        .addComponent(botonAceptar)
                        .addGap(68, 68, 68)
                        .addComponent(botonDivertido))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(68, 68, 68)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(pantallaError, javax.swing.GroupLayout.PREFERRED_SIZE, 293, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(jLabel2)
                                    .addComponent(jLabel3))
                                .addGap(18, 18, 18)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(fieldContrasena, javax.swing.GroupLayout.PREFERRED_SIZE, 124, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(textFieldUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, 123, javax.swing.GroupLayout.PREFERRED_SIZE))))
                        .addGap(77, 77, 77)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 95, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(textFieldUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(13, 13, 13)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(fieldContrasena, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(pantallaError, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(botonDivertido)
                    .addComponent(botonAceptar))
                .addGap(22, 22, 22))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    /**
     * Indica al programa que realizar cuando el botón de divertido es presionado.
     * @param evt Evento que sucede en la interfaz gráfica.
     */
    private void botonDivertidoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botonDivertidoActionPerformed
        JOptionPane.showMessageDialog(rootPane,"Es divertido :)");
        textFieldUsuario.setText("");
        fieldContrasena.setText("");
    }//GEN-LAST:event_botonDivertidoActionPerformed

    /**
     * Indica al programa que realizar al presionar el botón de aceptar.
     * @param evt Evento que sucede en la interfaz gráfica.
     */
    private void botonAceptarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botonAceptarActionPerformed
        pantallaError.setText("");
        String usuario=textFieldUsuario.getText();
        String contrasena=fieldContrasena.getText();
        if(!(usuario.equals("")|| contrasena.equals(""))){
            try{
                principal.usarUsuario(usuario);
               try{
                    principal.logIn(usuario, contrasena);
                    Principal.programa();
                    dispose();
                }catch(ContrasenaInvalida er){
                    pantallaError.setText(er.getMessage());
                }

            }catch(NoExisteUsuario err){
                javax.swing.JLabel label=new javax.swing.JLabel("<html><p align=center> Su usuario aún no existe <br> Para crearlo, repita su contraseña</html>");
                javax.swing.JPasswordField jpf = new javax.swing.JPasswordField();
                javax.swing.JOptionPane.showMessageDialog(null,
                new Object[]{label, jpf}, "Password:",
                javax.swing.JOptionPane.OK_CANCEL_OPTION);
                String contrasena2=jpf.getText();
                if(contrasena2.equals(contrasena)){
                    try{
                        principal.signIn(usuario, contrasena);
                        Principal.programa();
                        dispose();
                    }catch(Exception evr){
                        pantallaError.setText("<html>Error fatal: No se pudo crear el usuario <br> contacte a su proveedor </html>");
                    }
                }else{
                    pantallaError.setText("Las contraseñas no coinciden.");
                }
            }
            fieldContrasena.setText("");
        }
    }//GEN-LAST:event_botonAceptarActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton botonAceptar;
    private javax.swing.JButton botonDivertido;
    private javax.swing.JPasswordField fieldContrasena;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel pantallaError;
    private javax.swing.JTextField textFieldUsuario;
    // End of variables declaration//GEN-END:variables
}
